import { EMClient } from "../index";
import { setStatus } from "@/api/modules/im";
import { useImStore } from "@/stores/modules/im";
export const imReadAckListener = () => {
  const imStore = useImStore();
  const mountReadAckEventListener = () => {
    console.log("mountReadAckEventListener");
    EMClient.addEventHandler("aboutReadAckMessage", {
      onDeliveredMessage(message) {
        console.log("已送达客户端", message);
        updateMessageReadStatus(message);
      },
      onReceivedMessage(message) {
        console.log("已送达服务器", message);
        updateMessageReadStatus(message);
      },
      // 当前用户收到消息已读回执。
      onReadMessage: message => {
        console.log("已读", message);
        updateMessageReadStatus(message);
      },
      // 当前用户收到会话已读回执。
      onChannelMessage: message => {
        console.log("会话已读", message);
        updateConversationReadStatus(message);
      }
    });
  };
  const delayExec = fn => {
    let latestArgs = null;
    return function (...args) {
      latestArgs = args;
      setTimeout(() => {
        const argsToExecute = latestArgs;
        latestArgs = null;
        if (argsToExecute) {
          fn(...argsToExecute);
        }
      }, 1000);
    };
  };
  const setMessageStatus = (id, state) => {
    setStatus({
      status: state,
      mid: id
    }).then(res => {
      if (res.data) {
        imStore.setMessageStatus(id, state);
      }
    });
  };
  const debounceFnc = delayExec((...args) => {
    setMessageStatus(...args);
  });
  //根据收到的单条消息已读回执更新消息已读状态状态
  const updateMessageReadStatus = msg => {
    if (!msg.type) {
      //发送到服务器
      debounceFnc(msg.mid, 1);
    } else if (msg.type === "delivery") {
      //发送到客户端
      debounceFnc(msg.mid, 2);
    } else if (msg.type === "read" || msg.type === "channel") {
      //客户已读
      if (msg.mid == 0 || msg.type === "channel") {
        let arr = {
          items: []
        };
        Object.keys(this.statusList).map(key => {
          if (this.statusList[key] <= 2) {
            imStore.setMessageStatus(key, 3);
            arr.items.push({
              mid: key,
              status: 3
            });
          }
        });
        if (arr.items.length) {
          setStatus(arr);
        }
      } else {
        debounceFnc(msg.mid, 3);
      }
    }
  };
  //根据收到会话已读回执更新整个会话为已读状态
  const updateConversationReadStatus = () => {
    let arr = {
      items: []
    };
    Object.keys(imStore.messageStates).map(key => {
      if (imStore.messageStates[key] <= 2) {
        imStore.setMessageStatus(key, 3);
        arr.items.push({
          mid: key,
          status: 3
        });
      }
    });
    if (arr.items.length) {
      setStatus(arr);
    }
  };
  return {
    mountReadAckEventListener
  };
};
